//
//  SSMusicList.swift
//  QQ音乐
//
//  Created by 叶竞泽 on 2017/5/18.
//  Copyright © 2017年 叶竞泽. All rights reserved.
//

import UIKit
import AVFoundation

class SSMusicList: NSObject {

    /// 保存所有歌曲列表
    var musicList: [SSMusic]? {
        guard let path = Bundle.main.path(forResource: "Musics.plist", ofType: nil) else {
            return nil
        }
        let url = URL(fileURLWithPath: path)
        let array = NSArray(contentsOf: url) as? [[String: String]]
        var modelList = [SSMusic]()
        for i in 0 ..< array!.count {
            let music = SSMusic()
            music.name = array?[i]["name"]
            music.filename = array?[i]["filename"]
            music.lrcname = array?[i]["lrcname"]
            music.icon = array?[i]["icon"]
            music.singer = array?[i]["singer"]
            music.singerIcon = array?[i]["singerIcon"]
            modelList.append(music)
        }
        return modelList
    }
    
    static var shared: SSMusicList = {
        let musicList = SSMusicList()
        return musicList
    }()
    
    /// 存储所有播放器,key是歌名
    fileprivate var musicPlayerDict: [String: AVAudioPlayer]?
    
    /// 当前正在播放的歌曲
    var currentPlayingSong: SSMusic?
    
    override init() {
        super.init()
        self.createPlayers()
    }
    
    var players: [String: AVAudioPlayer]? {
        return SSMusicList.shared.musicPlayerDict
    }
    
    /// 根据歌名返回url
    func musicURL(withFileName fileName: String) -> URL? {
        guard let url = Bundle.main.url(forResource: fileName, withExtension: nil) else {
            return nil
        }
        return url
    }
    
    /// 根据音乐数据创建播放器
    fileprivate func createPlayers() {
        guard let count = musicList?.count else {
            return
        }
        musicPlayerDict = [String: AVAudioPlayer]()
        for i in 0 ..< count {
            guard let name = musicList?[i].filename, let url = musicURL(withFileName: name), let player = try? AVAudioPlayer(contentsOf: url), let key = musicList?[i].name else { continue }
            musicPlayerDict?[key] = player
        }
    }

}
